<!-- 网报功能 -->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
      @keyup.enter.native="getList()"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item
            label="单位名称"
            label-width="80px"
            prop="organizationName"
          >
            <m-select
              v-model="queryParams.organizationName"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="organizationName"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="合同编号" prop="agreementNumber">
            <el-input
              v-model="queryParams.agreementNumber"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系人" prop="contactsName">
            <el-input
              v-model="queryParams.contactsName"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row type="flex" justify="end" class="bloperation">
      <el-button class="blbutton" type="primary" size="mini" @click="openEditPw"
        >修改密码</el-button
      >
      <el-button
        class="blbutton"
        type="primary"
        size="mini"
        @click="openParticipant"
        >参与人员</el-button
      >
    </el-row>

    <!-- <el-progress type="circle" :width="60" :percentage="dataList[0].progressNum"></el-progress> -->
    <el-table
      :height="height - 450 + 'px'"
      v-loading="loading"
      :data="dataList"
      @row-dblclick="(row) => openhandleDialog(row, '3')"
    >
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="合同编号" align="center" prop="agreementNumber" />
      <el-table-column
        label="委托单位"
        align="center"
        prop="organizationName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="联系人"
        align="center"
        prop="contactsName"
        width="120"
      />
      <el-table-column
        label="联系电话"
        align="center"
        prop="contactsMobile"
        width="150"
      />
      <el-table-column
        label="单位地址"
        align="center"
        prop="organizationAddress"
        width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="检测人员"
        align="center"
        prop="personNum"
        width="80"
      />
      <el-table-column label="录入时间" align="center" prop="createTime" />
      <el-table-column label="年份" align="center" prop="year" width="100" />
      <el-table-column label="批次" align="center" prop="batchNum" width="60" />
      <!-- <el-table-column label="上传状态" align="center">
        <template slot-scope="{ row }">
          <i class="el-icon-success" style="font-size: 36px;color: #67c23a;"></i>
          <i class="el-icon-error" style="font-size: 36px;color: #f56c6c;"></i>
          <el-progress type="circle" :width="60" :percentage="row.progressNum + (row.isSuccess ? 20 : 0)"></el-progress>
        </template>
      </el-table-column> -->
      <el-table-column label="是否上传" align="center">
        <template slot-scope="{ row }">
          {{ row.platformSaveState == 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="是否提交" align="center">
        <template slot-scope="{ row }">
          {{ row.platformSubmitState == 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="{ row, $index }">
          <el-button
            @click.native.prevent="openhandleDialog(row, '3')"
            type="text"
          >
            详情
          </el-button>
          <el-button
            v-if="row.platformSaveState == 1"
            @click.native.prevent="handleOpenCard(row)"
            type="text"
          >
            报送卡
          </el-button>
          <el-button
            v-if="row.platformSubmitState != 1"
            @click.native.prevent="handleSubmitData(row, $index, 'save')"
            type="text"
          >
            保存
          </el-button>
          <el-button
            v-if="row.platformSaveState == 1 && row.platformSubmitState != 1"
            @click.native.prevent="handleSubmitData(row, $index, 'submit')"
            type="text"
          >
            提交
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加参与人员 -->
    <participant ref="participantRefs" />

    <!-- 登录失效 -->
    <el-dialog
      :visible.sync="loginVisible"
      width="500px"
      title="提示"
      @close="handleClose"
    >
      <el-alert
        title="登录状态失效，输入验证码后自动登录并上报数据"
        type="error"
        style="margin-bottom: 18px"
      >
      </el-alert>
      <el-form
        class="login-form"
        :model="submitForm"
        ref="submitForm"
        size="small"
        style="width: 100%"
      >
        <el-form-item prop="captcha">
          <div style="display: flex">
            <el-input
              v-model="submitForm.captcha"
              auto-complete="off"
              placeholder="验证码"
              style="flex: 1"
            >
              <svg-icon
                slot="prefix"
                icon-class="validCode"
                class="el-input__icon input-icon"
              />
            </el-input>
            <div class="login-code" @click="getPlatformCaptchaImages">
              <i class="el-icon-loading" v-if="captchaImageLoading"></i>
              <el-image
                v-else
                :src="codeUrl"
                style="width: 100%; height: 100%"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button
            :loading="submitloading"
            :disabled="submitForm.captcha && submitForm.sessionId"
            size="medium"
            type="primary"
            style="width: 100%"
            @click="(e) => handleSubmitInterface(e, true)"
          >
            <span>{{ submitForm.type == "save" ? "保存" : "提交" }}</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 详情弹框 -->
    <el-dialog
      :title="bltitle"
      :visible.sync="dialogVisiblehandle"
      :close-on-click-modal="false"
      width="1500px"
      class="bldialog"
      v-dialogDrag="true"
    >
      <el-form
        class="handleform"
        :disabled="blstatus != '1'"
        :rules="handlerRules"
        :model="handleform"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位名称">
              <el-input v-model="handleform.organizationName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-input
                v-model="handleform.agreementNumber"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="filterContact" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="filterMobile" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监测周期(天)">
              <el-input-number
                v-model="handleform.monitoringCycle"
                disabled
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监测启用状态">
              <el-select
                v-model="handleform.monitoringState"
                disabled
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.status_disable"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位地址">
              <el-input v-model="handleform.organizationAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="佩戴开始日期">
              <el-date-picker
                style="width: 100%"
                v-model="handleform.wearingBeginTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                :picker-options="pickerOptionsHandleF"
                placeholder="请选择"
                clearable
                @change="
                  (val) => handleChangeHandleWearTime(val, 'wearingEndTime')
                "
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="佩戴结束日期">
              <el-date-picker
                style="width: 100%"
                v-model="handleform.wearingEndTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                :picker-options="pickerOptionsHandleS"
                placeholder="请选择"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次" prop="batchNum">
              <el-input
                v-model="handleform.batchNum"
                placeholder="请输入1 - 4批号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="separate"></div>

      <!-- <div class="bloperation">
          <el-button class="blbutton" type="primary" size="mini" @click="uploadSubmission(0)">上传报送卡</el-button>
          <el-button class="blbutton" type="primary" size="mini" @click="handleShowJoin(0)">参与人员</el-button>
        </div> -->

      <el-table
        class="handletabel"
        ref="tableData"
        :class="blstatus == '2' && 'handletabelaudit'"
        v-loading="loadingHandle"
        :data="handleform.list"
        :row-class-name="tableRowClassName"
        :cell-class-name="tableCellClassName"
        height="356"
      >
        <el-table-column
          label="人员编号"
          align="center"
          prop="personnelNumber"
          width="100"
        />
        <el-table-column
          label="剂量计编号"
          align="center"
          prop="dosageNumber"
          width="120"
        />
        <el-table-column label="姓名" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <span>{{ scope.row.personnelName }}</span>
              <span v-if="scope.row.dosageType == 1">(内)</span>
              <span v-if="scope.row.dosageType == 2">(外)</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            <dict-tag
              :value="scope.row.personnelSex"
              :options="dict.type.sys_user_sex"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="职业类别"
          align="center"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <dict-tag
              :value="scope.row.occupationalClassification"
              :options="dict.type.occupational_classification"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="entrustDeptName" />
        <el-table-column label="剂量计佩戴起止日期" align="center" width="220">
          <template slot-scope="scope">
            <span>
              {{ parseTime(scope.row.wearingBeginTime, "{y}/{m}/{d}") }} -
              {{ parseTime(scope.row.wearingEndTime, "{y}/{m}/{d}") }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="寄出单号" align="center" prop="sendTrackingNumber" :width="blstatus != '3' && 130">
						<template slot-scope="scope">
							<span>{{scope.row.sendTrackingNumber}}</span>
						</template>
					</el-table-column> -->
        <el-table-column
          label="剂量当量1"
          align="center"
          prop="holeOneDosageValue"
          width="100"
        />
        <el-table-column
          label="剂量当量2"
          align="center"
          prop="holeTwoDosageValue"
          width="100"
        />
        <el-table-column
          label="剂量当量(mSv)"
          align="center"
          prop="dosageValue"
          width="120"
        />
      </el-table>

      <pagination
        style="margin-bottom: 5px"
        v-show="totalHandle > 0"
        :total="totalHandle"
        :page.sync="queryParamsHandle.pageNum"
        :limit.sync="queryParamsHandle.pageSize"
        @pagination="getListHandle"
      />

      <div slot="footer">
        <el-button
          v-if="blstatus == '1' || blstatus == '3'"
          @click="dialogVisiblehandle = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { entrustOrganizationList } from "@/api/person/entrustOrganization";
import {
  personalDosimeterDetail,
  getUnHandleWorkPersonnelList,
  getHandleData,
} from "@/api/slides/task";
import {
  getPlatformList,
  getPlatformIsExpires,
  getPlatformCaptchaImage,
  savePlatform,
  downloadSubmissionCard,
  submitPlatform,
  updatePwd,
} from "@/api/slides/uploads";
import { listByIds } from "@/api/system/oss";

import MSelect from "@/components/mSelect";
import Participant from "./components/uploads/participant";
export default {
  name: "Uploadss",
  dicts: ["is_or_no", "platform_upload_state"],
  components: {
    MSelect,
    Participant,
  },
  data() {
    return {
      loginVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        organizationName: "",
        agreementNumber: "",
        contactsName: "",
      },
      // 单位相关字段
      entrustOrganizationSelect: [],
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      // 视图高度
      height: document.documentElement.clientHeight,
      loading: false,
      total: 0,
      dataList: [],
      visible: false,
      // 登录
      submitForm: {
        code: "",
      },
      codeUrl: "",
      captchaImageLoading: false,
      submitloading: false,
      // 办理弹框
      totalHandle: 0,
      loadingHandle: false,
      dialogVisiblehandle: false,
      handleform: {},
      blstatus: null,
      bltitle: null,
      queryParamsHandle: {
        pageNum: 1,
        pageSize: 10,
        searchStr: "",
      },
      handlerRules: {
        batchNum: [
          { required: true, message: "批号不能为空", trigger: "blur" },
          {
            pattern: /^[1-4]$/,
            message: "批号只能1-4",
            trigger: "blur",
          },
        ],
      },
      pickerOptionsHandleF: {
        // disabledDate: (time) => {
        //   return time.getTime() > new Date(this.handleform.wearingEndTime).getTime();
        // },
      },
      pickerOptionsHandleS: {
        // disabledDate: (time) => {
        //   return time.getTime() < new Date(this.handleform.wearingBeginTime).getTime();
        // },
      },
      // 办理弹框END

      viewNetworkSessionId: "",
    };
  },
  computed: {
    networkSessionId() {
      return localStorage.getItem("network-sessionId");
    },
    filterContact() {
      return this.handleform.dosageContactsName || this.handleform.contactsName;
    },
    filterMobile() {
      return (
        this.handleform.dosageContactsMobile || this.handleform.contactsMobile
      );
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取任务列表
    getList() {
      this.loading = true;
      getPlatformList(this.queryParams)
        .then((response) => {
          this.dataList =
            response.rows.reduce((pre, cur) => {
              cur.progressNum = 0; // 进度条
              cur.btnDisabled = false; // 是否可点击
              cur.isSuccess = 0; // 是否可点击
              cur.isSuccess = 0; // 是否可点击
              pre.push(cur);
              return pre;
            }, []) || [];
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 切换tab栏
    changeTab(tab) {
      this.queryParams.tasksState = tab.name;
      this.dataList = [];
      this.getList();
    },
    // 打开办理对话框
    openhandleDialog(row, status) {
      this.handleform = {};
      this.openRowHandle = row;
      this.handleform.taskPersonalDosimeterId = row.taskPersonalDosimeterId;
      if (status == "3") {
        this.blstatus = "3";
        this.bltitle = "查看外照射任务";
      }
      personalDosimeterDetail(row.taskPersonalDosimeterId).then((response) => {
        if (response.data) {
          if (response.data.monitoringState != null) {
            response.data.monitoringState =
              response.data.monitoringState.toString();
          }
          this.handleform = response.data;
          this.handleform.operationList = [];
          this.handleId = row.taskPersonalDosimeterId;
          this.queryParamsHandle = {
            pageNum: 1,
            pageSize: 10,
            searchStr: "",
          };
          this.getListHandle();
          this.dialogVisiblehandle = true;
        }
      });
      // 获取未办理人员下拉框
      getUnHandleWorkPersonnelList(row.taskPersonalDosimeterId).then(
        (response) => {
          // if(response.data && response.data.length != 0) {
          this.unHandleWorkPersonnelList = response.data || [];
          this.unHandleWorkPersonnelList.forEach((item) => {
            item.showTypeName =
              item.personnelName +
              (item.dosageType == "1"
                ? "(内)"
                : item.dosageType == "2"
                ? "(外)"
                : "");
            item.originName = item.personnelName;
            item.isEmptyTrackingNumber = !item.sendTrackingNumber;
          });
          // }
        }
      );
    },
    // 列表标红
    tableRowClassName({ row, rowIndex }) {
      if (
        (this.largeDose && row.dosageValue > this.largeDose) ||
        row.exceptional
      ) {
        return "warning-row";
      }
      return "";
    },
    // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    // 分页获取人员（根据row.taskPersonalDosimeterId）
    getListHandle() {
      this.queryParamsHandle.id = this.handleId;
      this.loadingHandle = true;
      getHandleData(this.queryParamsHandle)
        .then((response) => {
          this.handleform.list = response.rows || [];
          if (this.handleform.list.length != 0) {
            this.handleform.list.forEach((item) => {
              item.showTypeName =
                item.personnelName +
                (item.dosageType == "1"
                  ? "(内)"
                  : item.dosageType == "2"
                  ? "(外)"
                  : "");
              item.originName = item.personnelName;
              item.isEmptyTrackingNumber = !item.sendTrackingNumber;
            });
          }
          this.totalHandle = response.total;
          this.loadingHandle = false;
        })
        .catch((response) => {
          this.loadingHandle = false;
        });
    },
    getCode() {
      console.log(this.networkSessionId);
    },
    openParticipant() {
      this.$refs.participantRefs.openDialog();
    },
    // 打开修改密码弹窗
    openEditPw() {
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          updatePwd({
            password: value,
          }).then((res) => {
            res.code == 200 &&
              this.$message({
                type: "success",
                message: "修改成功",
              });
          });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },
    // 保存/提交
    handleSubmitData(row, index, type) {
      // 是否过期
      getPlatformIsExpires().then((res) => {
        const isExpired = res.data;
        this.submitForm.type = type;
        this.submitForm.taskPersonalDosimeterId = row.taskPersonalDosimeterId;
        this.submitForm.platformDataId = row.platformDataId;
        if (isExpired) {
          this.getPlatformCaptchaImages();
          this.loginVisible = true;
          // this.$set(row, 'showLogin', !row.showLogin)
        } else {
          this.handleSubmitInterface();
        }
        console.log(res);
      });
    },
    // 获取图片验证码
    getPlatformCaptchaImages() {
      this.captchaImageLoading = true;
      getPlatformCaptchaImage()
        .then((res) => {
          this.codeUrl = `data:image/png;base64,${res.data.image}`;
          this.viewNetworkSessionId = res.data.sessionId;
          localStorage.setItem("network-sessionId", res.data.sessionId);
        })
        .catch((err) => {})
        .finally(() => {
          this.captchaImageLoading = false;
        });
    },
    handleOpenCard(row) {
      listByIds(row.platformSubmissionCardOssId).then((response) => {
        window.open(response?.data[0]?.url, "PDF", "");
      });
    },
    // 动画效果
    animationRow() {
      let timeout = null;
      // 当前提交id对应数据
      const taskPersonalDosimeterId = this.submitForm.taskPersonalDosimeterId;
      const row = this.dataList.find(
        (i) => i.taskPersonalDosimeterId == taskPersonalDosimeterId
      );

      row.progressNum = 0;
      timeout = setInterval(() => {
        if (row.progressNum >= 80) {
          clearInterval(timeout);
          timeout = null;
          return;
        }
        this.$set(row, "progressNum", row.progressNum + 20);
      }, 1000);
    },
    /**
     * 赋值数据是否提交成功
     * @param type 0 失败 1 成功
     */
    isUploadSuccess(type) {
      const taskPersonalDosimeterId = this.submitForm.taskPersonalDosimeterId;
      const row = this.dataList.find(
        (i) => i.taskPersonalDosimeterId == taskPersonalDosimeterId
      );
      this.$set(row, "isSuccess", type);
    },
    // 提交数据
    handleSubmitInterface(e, loginFlag = false) {
      /**
       * taskPersonalDosimeterId: '', // 计量计任务id
       *   captcha: '', // 验证码code
       *   sessionId: this.networkSessionId, // 会话id
       *   loginFlag, // 是否重新登录
       *   platformDataId: '', // 平台上传数据id
       */
      let query = {
        ...this.submitForm,
        sessionId: this.viewNetworkSessionId || this.networkSessionId,
        loginFlag,
      };
      this.submitloading = true;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const funs = [
        { type: "save", fun: savePlatform },
        { type: "submit", fun: submitPlatform },
        { type: "dowmload", fun: downloadSubmissionCard },
      ];
      // 启动动画
      // this.animationRow()

      const fun = funs.find((i) => i.type == query.type);
      fun
        .fun(query)
        .then((response) => {
          this.getList();
          this.closeDialog();
          this.loginVisible = false;
          this.isUploadSuccess(1);
          this.$modal.msgSuccess(
            `${query.type == "save" ? "保存" : "提交"}成功`
          );
        })
        .catch((err) => {
          console.log(err);
          this.isUploadSuccess(0);
          this.$modal.msgError(err || "上传失败，请重试");
        })
        .finally(() => {
          this.submitloading = false;
          loading.close();
        });
      console.log(query);
    },
    closeDialog() {},
    handleClose() {
      this.submitForm = {
        code: "",
      };
    },
    reset() {
      this.resetForm("queryParams");
      this.getList();
    },
  },
};
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 6px auto 4px;
  .login-code {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30%;
    height: 32px;
    cursor: pointer;
    margin-left: 8px;
  }
}
.app-container {
  .el-dialog__wrapper {
    background-color: rgba($color: #000000, $alpha: 0.4);
  }
}
.bloperation {
  margin-bottom: 8px;
}
</style>
